// Like.js - 点赞模型
const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');

/**
 * 点赞模型类
 * 映射数据库likes表，提供点赞相关的数据访问和方法
 */
class Like {
  constructor() {
    // 定义模型结构
    this.model = sequelize.define('Like', {
      id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true
      },
      user_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id'
        },
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
      },
      video_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: {
          model: 'videos',
          key: 'id'
        },
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE'
      },
      created_at: {
        type: DataTypes.DATE,
        allowNull: false
      },
      updated_at: {
        type: DataTypes.DATE,
        allowNull: false
      }
    }, {
      tableName: 'likes',
      timestamps: false,
      indexes: [
        {
          unique: true,
          fields: ['user_id', 'video_id']
        },
        {
          fields: ['user_id']
        },
        {
          fields: ['video_id']
        }
      ]
    });
  }

  /**
   * 用户点赞视频
   * @param {number} userId - 用户ID
   * @param {number} videoId - 视频ID
   * @returns {Promise<Object>} - 创建的点赞记录
   */
  async create(userId, videoId) {
    try {
      const now = new Date();
      const like = await this.model.create({
        user_id: userId,
        video_id: videoId,
        created_at: now,
        updated_at: now
      });
      return like;
    } catch (error) {
      console.error('创建点赞记录失败:', error);
      throw error;
    }
  }

  /**
   * 用户取消点赞
   * @param {number} userId - 用户ID
   * @param {number} videoId - 视频ID
   * @returns {Promise<number>} - 删除的记录数
   */
  async destroy(userId, videoId) {
    try {
      const result = await this.model.destroy({
        where: {
          user_id: userId,
          video_id: videoId
        }
      });
      return result;
    } catch (error) {
      console.error('取消点赞失败:', error);
      throw error;
    }
  }

  /**
   * 检查用户是否已点赞视频
   * @param {number} userId - 用户ID
   * @param {number} videoId - 视频ID
   * @returns {Promise<boolean>} - 是否已点赞
   */
  async checkLike(userId, videoId) {
    try {
      const like = await this.model.findOne({
        where: {
          user_id: userId,
          video_id: videoId
        }
      });
      return !!like;
    } catch (error) {
      console.error('检查点赞状态失败:', error);
      throw error;
    }
  }

  /**
   * 获取视频的点赞数
   * @param {number} videoId - 视频ID
   * @returns {Promise<number>} - 点赞数
   */
  async getLikeCount(videoId) {
    try {
      const count = await this.model.count({
        where: {
          video_id: videoId
        }
      });
      return count;
    } catch (error) {
      console.error('获取点赞数失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户点赞的视频列表
   * @param {number} userId - 用户ID
   * @param {number} page - 页码
   * @param {number} pageSize - 每页数量
   * @returns {Promise<Array>} - 视频列表
   */
  async getUserLikedVideos(userId, page = 1, pageSize = 10) {
    try {
      const offset = (page - 1) * pageSize;
      const likes = await this.model.findAll({
        where: {
          user_id: userId
        },
        attributes: ['video_id'],
        limit: pageSize,
        offset: offset,
        order: [['created_at', 'DESC']]
      });
      return likes.map(like => like.video_id);
    } catch (error) {
      console.error('获取用户点赞视频列表失败:', error);
      throw error;
    }
  }
}

module.exports = new Like();